#include "DeadProxySprReader.h"
#include "DeadProxyDatReader.h"
#include <stdio.h>

SprReader::SprReader(wxString * filename)
{
    SprFile = new wxFile(filename->c_str());
}

SprReader::~SprReader()
{
    SprFile->Close();
    delete SprFile;
}

unsigned char * SprReader::GetSprite(int spriteid)
{
    //wxString output;
    unsigned char * ret = (unsigned char*)malloc(32*32*4);
    memset(ret, 0, 32*32*4); //init to black alpha
    int SpritePtr = spriteid * 4 + 6;
    int SpriteAddr = 0;
    short AlphaCount;
    short PixelCount;
    unsigned int ipos = 0;
    unsigned short fpos = 0;
    int i;
    unsigned short len = 0;
    SprFile->Seek(SpritePtr, wxFromStart);
    SprFile->Read(&SpriteAddr, 4);
    SprFile->Seek(SpriteAddr, wxFromStart);
    SprFile->Seek(3, wxFromCurrent);
    SprFile->Read(&len, 2);
    //output.Printf("SpritePtr = %i, SpriteAddr = %i, len = %i", SpritePtr, SpriteAddr, len);
    //wxMessageBox(output);
    while(fpos < len)
    {
        SprFile->Read(&AlphaCount, 2);
        SprFile->Read(&PixelCount, 2);
        fpos = fpos + 4; //we read 4 bytes
        ipos = ipos + AlphaCount; //skip alpha bytes, we initialized it to alpha
        for(i = 0; i < PixelCount; i++)
        {
            SprFile->Read((void*)(ret + ipos * 4), 3); //Read the data color
            ret[ipos * 4 + 3] = 0xFF; //Make opaque
            //output.Printf("%i:%i:%i:%i", 0xFF && *(int*)(ret + 0), 0xFF && *(int*)(ret + 1), 0xFF && *(int*)(ret + 2), 0xFF && *(int*)(ret + 3));
            //wxMessageBox(output);
            ipos = ipos + 1; //we moved forward one pixel
            fpos = fpos + 3; //and 3 bytes in the file
        }
    }
    //memset(ret, 127, 32*32*4); //init to black alpha
    return ret;
}
    
    
